<template>
  <div>
    <el-form ref="form" :model="formData" :rules="rules">
      <el-table :data="currentPageData" style="width: 100%">
        <!-- 表格列定义 -->
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="名称">
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + (scope.$index + (currentPage - 1) * pageSize) + '.name'" :rules="rules.name">
              <el-input v-model="formData.tableData[scope.$index + (currentPage - 1) * pageSize].name"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 更多列... -->
      </el-table>
      <el-pagination
          @current-change="handlePageChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :total="formData.tableData.length">
      </el-pagination>
      <el-button type="primary" @click="submitAllPages">提交</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        tableData: this.generateDefaultTableData(200) // 初始化时生成15条默认数据
      },
      currentPage: 1, // 当前页码
      pageSize: 5,   // 每页大小
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    currentPageData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.formData.tableData.slice(start, end);
    }
  },
  methods: {
    generateDefaultTableData(count) {
      const defaultData = [];
      for (let i = 1; i <= count; i++) {
        defaultData.push({
          id: i,
          name: `默认名称${i}`, // 你可以根据需要设置默认值
          // 其他字段...
        });
      }
      return defaultData;
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.validateCurrentPage();
    },
    async validateCurrentPage() {
      try {
        await this.$refs.form.validate();
        return true;
      } catch (error) {
        return false;
      }
    },
    async submitAllPages() {
      for (let i = 1; i <= Math.ceil(this.formData.tableData.length / this.pageSize); i++) {
        this.currentPage = i; // 切换到下一页
        await this.$nextTick(); // 等待DOM更新

        if (!(await this.validateCurrentPage())) {
          this.$message.error(`第 ${i} 页存在未通过校验的数据，请检查后重试。`);
          return; // 如果当前页有校验失败的数据，就停留在当前页并退出循环
        }
      }
      // 如果所有页都通过了校验，执行提交逻辑
      console.log('所有页面数据均通过校验，可以提交');
    }
  }
};
</script>